$(document).ready(function(){
	var lnglatMap = {};

	var isSearch = 0;
	//创建地图
   	var map = new AMap.Map('container',{
        resizeEnable: true,
        zoom: 15,
        animateEnable: true,
        lang: "zh_cn",
        zoomEnable: true,
        features:["bg","point","road","building"],
        center: [113.927,22.532984]
    });	

    var markers = [];

	var sortTime = 0;

	access_token = $.getCookie("access_token");
	if($('.access_token').val() != "" && $('.access_token').val() != null){
		access_token = $('.access_token').val();
		if($.getCookie("access_token") == null){
			$.setCookie("access_token", access_token);
		}		
	}
	//绑定地图图标
	function boundMakerClick(boundId){
	    $('#'+boundId).click(function(){
	    	var lnglat = new AMap.LngLat(lnglatMap[$(this).attr('id').toString()].toString().split(',')[0],lnglatMap[$(this).attr('id').toString()].toString().split(',')[1]);

			var info = new AMap.InfoWindow({
				isCustom:true,
		        content:"<div class='mapMarkInfo' ><img class='mapMarkInfo-img' src='"+$(this).children('.nearby-row-shop-img').attr('src')+"'>&nbsp;"+$(this).children('.nearby-row-shop-message').children('.nearby-row-shop-name').text()+"<div class='arrow'></div></div>",
		        offset:new AMap.Pixel(0,-25)
		    });

	    	info.open(map,[lnglatMap[$(this).attr('id').toString()].toString().split(',')[0],lnglatMap[$(this).attr('id').toString()].toString().split(',')[1]]);
			map.setCenter(lnglat);
	    })	
	}

	var isLoad = 0;
	$.popTagShow(2,'加载附近列表中','请稍后',null,null,null,null,null,null);
	//展示附近信息
	$.loadMessage = function(){
		$('.not-open-location').hide();
		isLoad = 1;
		$.getJSON("/"+server+"/nearbyGetList?access_token="+access_token+"&lat="+lat+"&lng="+lng+"&sortTime="+sortTime,function(json){
			if(sortTime == 0){
				$('.row-message').remove();
				isSearch = 0;
			}
			sortTime = json.sortTime;
			$('.loading-more').hide();
			for (var i = 0;i < json.data.length; i++) {
				$('.load-message').append(
					'<div class="row-message" id="row-message-'+json.data[i].shopModel.id+'">'+
						'<img class="nearby-row-shop-img" src="'+json.data[i].shopModel.logo+'">'+
						'<div class="nearby-row-shop-message">'+
							'<strong class="nearby-row-shop-name">'+json.data[i].shopModel.name+'</strong>'+
							'<br/>'+
							'<span class="nearby-row-shop-address">'+json.data[i].shopModel.address+'</span>'+
						'</div>'+
						'<div class="nearby-row-borrow-num">'+
							'<div id="indicatorContainer-'+json.data[i].shopModel.id+'" class="nearby-row-borrow-num-left" ><span>可借</span></div>'+
							'<div id="indicatorContainer-'+json.data[i].shopModel.id+'-2" class="nearby-row-borrow-num-right" ><span>可还</span></div>'+
						'</div>'+
						'<img class="nearby-row-line" src="/static/images/nearby-line.png">'+
					'</div>'
				);

				lnglatMap['row-message-'+json.data[i].shopModel.id] = json.data[i].shopModel.lng+','+json.data[i].shopModel.lat;

			    $('#indicatorContainer-'+json.data[i].shopModel.id).radialIndicator({
				    barColor : '#6DDAE9',
				    barWidth : 10,
				    initValue : json.data[i].shopModel.canBorrowCnt,
				    maxValue: json.data[i].shopModel.canBorrowCnt+json.data[i].shopModel.canReturnCnt,
				    fontColor:'#000000',
				    roundCorner:true,
				    // barColor: '#00000'
			    });

			    $('#indicatorContainer-'+json.data[i].shopModel.id+'-2').radialIndicator({
				    barColor : '#f59882',
				    barWidth : 10,
				    initValue : json.data[i].shopModel.canReturnCnt,
				    maxValue: json.data[i].shopModel.canBorrowCnt+json.data[i].shopModel.canReturnCnt,
				    fontColor:'#000000',
				    roundCorner:true,
				    // barColor: '#00000'
			    }); 	

				var marker = new AMap.Marker({
					icon: icon,
					position: [json.data[i].shopModel.lng,json.data[i].shopModel.lat],
					offset: new AMap.Pixel(-12,-12),
					zIndex: 101,
					map: map
				});	

				markers.push(marker);

				boundMakerClick('row-message-'+json.data[i].shopModel.id);
		
		    }
		    isLoad = 0;
			if(sortTime == -1){
				$(".load-message").append(
					'<div class="no-data" style="text-align:center;font-size:1em">'+
						'没有更多了！'+
					'</div>'
				)
			}					    
		});	
	}

	//使用高德导航进行定位
	map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition:'RB'
        });
        // map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });
    //解析定位结果
    function onComplete(data) {
    	$.popTagHide();
		lat = data.position.getLat(); // 纬度，浮点数，范围为90 ~ -90
        lng = data.position.getLng(); // 经度，浮点数，范围为180 ~ -180。	
        if(lat == 0 && lng == 0){
        	$('.not-open-location').show();
        }
        else{
        	$.loadMessage();
        }

        var lnglat = new AMap.LngLat(lng,lat);
		map.setCenter(lnglat);

		var icon2 = new AMap.Icon({
			image: 'http://ditu.amap.com/assets/img/loc.png',
			size: new AMap.Size(20, 20),
			imageSize:new AMap.Size(20, 20)
		});	

		var marker = new AMap.Marker({
			icon: icon2,
			position: [lng,lat],
			offset: new AMap.Pixel(-12,-12),
			zIndex: 101,
			map: map
		});	        
    }
    //处理失败定位
    function onError(data){
    	$('.not-open-location').show();
    }

	// $(window).scroll(function() {
	// 	if(isSearch == 0){
	// 		if($(document).scrollTop() + $(window).height() >= $(document).height()-500){
	// 			if(sortTime != -1 && isLoad == 0){
	// 				isLoad = 1;				
	// 				$('.loading-more').show();
	// 				$.loadMessage();
	// 			}
	// 		}
	// 	}
	// });	

       var nDivHight = $(".load-message").height();
       $(".load-message").scroll(function(){
         	nScrollHight = $(this)[0].scrollHeight;
         	nScrollTop = $(this)[0].scrollTop;
         	if(isSearch == 0){
         		if(nScrollTop + nDivHight >= (nScrollHight-100)){
           			if(sortTime != -1 && isLoad == 0){
						isLoad = 1;				
						$('.loading-more').show();
						$.loadMessage();
					}
				}
           	}
        });

	var icon = new AMap.Icon({
		image: 'http://7xkkzi.com2.z0.glb.qiniucdn.com/cdtNearAnnotation.png',
		size: new AMap.Size(20, 27),
		imageSize:new AMap.Size(20, 27)
	});	
	//展示搜索信息
	$.loadSearchMessage = function(){
		$('.row-message').remove();
		$('.no-data').remove();
		$('.loading-more').show();
		$('.not-open-location').hide();
		for(var i=markers.length-1;i>-1;i--){
    		// alert(markers[i]);
    		markers[i].setMap(null);
    		markers.splice(i,1);
    	}
    	isSearch = 1;
		$.getJSON("/"+server+"/searchNearbyList?access_token="+access_token+"&lat="+lat+"&lng="+lng+"&keyword="+$('.searchKeyWords').val(),function(json){
					$('.loading-more').hide();
					for (var i = 0;i < json.data.length; i++) {
						$('.load-message').append(
							'<div class="row-message" id="row-message-'+json.data[i].shopModel.id+'">'+
								'<img class="nearby-row-shop-img" src="'+json.data[i].shopModel.logo+'">'+
								'<div class="nearby-row-shop-message">'+
									'<strong class="nearby-row-shop-name">'+json.data[i].shopModel.name+'</strong>'+
									'<br/>'+
									'<span class="nearby-row-shop-address">'+json.data[i].shopModel.address+'</span>'+
								'</div>'+
								'<div class="nearby-row-borrow-num">'+
									'<div id="indicatorContainer-'+json.data[i].shopModel.id+'" class="nearby-row-borrow-num-left" ><span>可借</span></div>'+
									'<div id="indicatorContainer-'+json.data[i].shopModel.id+'-2" class="nearby-row-borrow-num-right" ><span>可还</span></div>'+
								'</div>'+
								'<img class="nearby-row-line" src="/static/images/nearby-line.png">'+
							'</div>'
						);

						lnglatMap['row-message-'+json.data[i].shopModel.id] = json.data[i].shopModel.lng+','+json.data[i].shopModel.lat;

					    $('#indicatorContainer-'+json.data[i].shopModel.id).radialIndicator({
						    barColor : '#6DDAE9',
						    barWidth : 10,
						    initValue : json.data[i].shopModel.canBorrowCnt,
						    maxValue: json.data[i].shopModel.canBorrowCnt+json.data[i].shopModel.canReturnCnt,
						    fontColor:'#000000',
						    roundCorner:true,
						    // barColor: '#00000'
					    });

					    $('#indicatorContainer-'+json.data[i].shopModel.id+'-2').radialIndicator({
						    barColor : '#f59882',
						    barWidth : 10,
						    initValue : json.data[i].shopModel.canReturnCnt,
						    maxValue: json.data[i].shopModel.canBorrowCnt+json.data[i].shopModel.canReturnCnt,
						    fontColor:'#000000',
						    roundCorner:true,
						    // barColor: '#00000'
					    }); 	

						var marker = new AMap.Marker({
							icon: icon,
							position: [json.data[i].shopModel.lng,json.data[i].shopModel.lat],
							offset: new AMap.Pixel(-12,-12),
							zIndex: 101,
							map: map
						});	

						markers.push(marker);

						boundMakerClick('row-message-'+json.data[i].shopModel.id);
				
				    }
				    isLoad = 0;
					if(sortTime == -1){
						$(".load-message").append(
							'<div class="no-data" style="text-align:center;font-size:1em">'+
								'没有相关内容！'+
							'</div>'
						)
					}					    
		});			
	};

    $('.searchKeyWords').keyup(function(){
    	// for(var i=markers.length-1;i>-1;i--){
    	// 	// alert(markers[i]);
    	// 	markers[i].setMap(null);
    	// 	markers.splice(i,1);
    	// }
    	// alert(markers.length);
    	// $.loadSearchMessage();
    	if($(this).val() != ""){
    		$('.search-icon2').show();
    	}
    	else{
    		$('.search-icon2').hide();
    		sortTime = 0;
    		$.loadMessage();
    	}
    });

    $('.search-icon').click(function(){
    	if($('.searchKeyWords').val() != ""){
    		$.loadSearchMessage();
    	}
    });

    $('.search-icon2').click(function(){
    	$('.searchKeyWords').val("");
    	$('.search-icon2').hide();
    	sortTime = 0;
    	$.loadMessage();
    });

    $(".searchKeyWords").keydown(function(e){ 
		var curKey = e.which; 
		if(curKey == 13){ 
			if($(this).val() != ""){
				$('.searchKeyWords').blur();
				$.loadSearchMessage();
			}
		} 
	});

})